#!/bin/bash

today=`date +"%Y-%m-%d"`
# def_data_dir=/data/backup/es/$today
def_data_dir=/home/wzq/tmp/es2/$today
read -e -p "data folder : " -i $def_data_dir 	date_dir
echo "data folder="$date_dir


es_url=http://localhost:9200
function rmoveAndrestoreOneIndex {
	index=$1
	index_url=$es_url/$index
	input=$date_dir/$index.json
	echo "********************************"
	echo "input     : "$date_dir/$index.json
	echo "index     : "$index
	echo "index_url : "$index_url
	curl -X DELETE $index_url 
	# >> /dev/null
	elasticdump --input=$input --output=$index_url --type=data  
	# >> /dev/null
}

# for file in $date_dir/*
# do
# 	ehoc $file
# done


cd $date_dir
for file in `ls`
do
	# logstash_api-yyyymmdd
	dt="${file:13:8}"
	# echo $dt
	if [ -z $begin ];then
		begin=$dt
		end=$dt
	fi
	if [ "$begin" -gt "$dt" ]; then
		begin=$dt
	fi

	if [ "$end" -lt "$dt" ]; then
		end=$dt
	fi
done

begin=`date +"%Y-%m-%d" -d $begin`
end=`date +"%Y-%m-%d" -d $end`
# echo "begin=$begin end=$end"
read -e -p "begin date(include)  : " -i $begin		begin
read -e -p "end date  (include)  : " -i $end      	end
echo "begin=$begin end=$end"
begin=`date +"%Y%m%d" -d $begin`
end=`date +"%Y%m%d" -d $end`
echo "begin=$begin end=$end"

cd $date_dir
for file in `ls`
do
	# filename=$(basename "$file")
	# extension="${filename##*.}"
	# filename="${filename%.*}"
	# # echo $file
	# # echo $extension
	# # echo $filename
	# if [ $extension = json ];then
	# 	rmoveAndrestoreOneIndex $filename
	# fi

	# logstash_api-yyyymmdd
	filename="${file:0:21}"
	dt="${file:13:8}"
	if [ "$dt" -ge $begin ] && [ "$dt" -le $end ]; then
		# echo $filename
		rmoveAndrestoreOneIndex $filename
	fi
done


# for (( i=10; i<20; i++)); do echo $i; done;